import React, { useEffect, useState } from 'react'
import { FixedSizeList as List, ListChildComponentProps } from 'react-window'
import AutoSizer from 'react-virtualized-auto-sizer'
import { IconToggleOrgTree, OrgTreeItem, OrgTreeItemName, Wrap } from './style'
import { OrgTreeModel } from './translator'
import { useOrgTreeStore } from './store'
import { flatOrgTreeToList } from './utils'
import { orgItemCheck } from '@/pages/manager/store.orgTree'

interface RowRendererProps extends ListChildComponentProps {
	data: OrgTreeModel[]
}
const rowRenderer = React.memo(({ data: list, index, style }: RowRendererProps) => {
	const rowData = list[index]
	const { id, org, status, children, nestingLevel } = rowData
	const toggleTree = useOrgTreeStore((state) => state.toggleTree)
	const handleToggleTree = () => {
		toggleTree(rowData)
	}
	const handleCheck = () => {
		orgItemCheck(rowData)
	}
	return (
		<div style={style}>
			<OrgTreeItem nestingLevel={nestingLevel} isCascade={children.length > 0}>
				{children.length > 0 && <IconToggleOrgTree open={status.isOpen} onClick={handleToggleTree} />}
				<OrgTreeItemName checked={status.isChecked} onClick={handleCheck}>
					<span>{org.name}</span>
					{id === 'liveList' ? (
						<span> ({org.userSize}) </span>
					) : (
						<span>
							{' '}
							({org.userOnlineSize}/{org.userSize}){' '}
						</span>
					)}
				</OrgTreeItemName>
			</OrgTreeItem>
		</div>
	)
})
export const OrganizeTree = () => {
	const [list, setList] = useState<OrgTreeModel[]>([])
	const tree = useOrgTreeStore((state) => state.tree)
	useEffect(() => {
		const result = flatOrgTreeToList(tree)
		setList(result)
	}, [tree])
	return (
		<Wrap>
			<AutoSizer>
				{({ width, height }) => (
					<List
						width={width}
						height={height}
						itemCount={list.length}
						itemSize={24}
						itemData={list}
						itemKey={(index, data) => `${data[index].id}_${index}`}
					>
						{rowRenderer}
					</List>
				)}
			</AutoSizer>
		</Wrap>
	)
}
